//
//  ListOfFacts_VC.m
//  WorldOfFacts_V2
//
//  Created by Denis Demjanko on 08.11.12.
//  Copyright (c) 2012 it-dimension. All rights reserved.
//

#import "ListOfFacts_VC.h"
#import "ListOfFactsCell.h"
#import "SVPullToRefresh.h"
#import "Service.h"
#import "DataBase.h"
#import "DetailFact_VC.h"
#import "WBSuccessNoticeView.h"

@implementation ListOfFacts_VC

@synthesize segmentedControl,table;

#pragma mark - init

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"Мир фактов";
    }
    return self;
}

- (void)setNavTitle:(NSString *)title
{
    UILabel *titleView = (UILabel *)self.navigationItem.titleView;
    if (!titleView) {
        titleView = [[UILabel alloc] initWithFrame:CGRectZero];
        titleView.backgroundColor = [UIColor clearColor];
        titleView.font = [UIFont boldSystemFontOfSize:20.0];
        titleView.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
        
        titleView.textColor = [UIColor colorWithRed:187.0f/255.0f green:187.0f/255.0f blue:187.0f/255.0f alpha:1.0f]; // Change to desired color
        
        self.navigationItem.titleView = titleView;
    }
    
    titleView.text = title;
    [titleView sizeToFit];
}

#pragma mark - View Life

- (void)viewDidLoad{
    [super viewDidLoad];
        
    [self restoreFactsOptions];
    [self configureTable];
    [self initFacts];
    [self addCategoryIcon];
    [self registerNotifications]; 
    [self setNavTitle:@"Мир фактов"];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    if(factsType==Unread){
        [factsArray removeAllObjects];
        [factsArray addObjectsFromArray:[[DataBase sharedManeger]getFacts:factCategory fromFact_id:0 factType:factsType]];
        [table reloadData];
    }
}

-(void)configureTable{
    __unsafe_unretained id weakSelf = self;
        
    table.showsInfiniteScrolling = TRUE;
    table.showsPullToRefresh = TRUE;
    
    [table addPullToRefreshWithActionHandler:^{
        [weakSelf refreshFacts];
    }];
    
    [table addInfiniteScrollingWithActionHandler:^{
        [weakSelf performSelector:@selector(loadMoreFacts) withObject:nil afterDelay:0.8f];
    }];
    
    if([[NSUserDefaults standardUserDefaults] objectForKey:@"facts_update"])
        table.pullToRefreshView.lastUpdatedDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"facts_update"];
}

-(void)initFacts{
    factsArray = [[NSMutableArray alloc] initWithArray:[[DataBase sharedManeger]getFacts:factCategory fromFact_id:0 factType:factsType]];
    
    [self checkMoreAvailablesFacts];        
}

#pragma mark - Facts Options

-(void)addCategoryIcon{
    return;
    
    if(!category_icon){
        category_icon = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 34, 34)];
        category_icon.image = [UIImage imageNamed:@"0189"];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:category_icon];
    }
    
    if([[NSUserDefaults standardUserDefaults] objectForKey:@"category"])
        category_icon.image = [UIImage imageNamed:[[[NSUserDefaults standardUserDefaults] objectForKey:@"category"] valueForKey:@"icon"]];    
}

-(void)restoreFactsOptions{    
    factsType = ReadUnread;
    factCategory = [[[[NSUserDefaults standardUserDefaults] objectForKey:@"category"] valueForKey:@"id"] intValue];
}

#pragma mark - Service

-(void)refreshFacts{    
    int fact_id = [[DataBase sharedManeger] getLastFactId];
        

    [[Service sharedManeger] getNewFacts:fact_id withHandler:^(NSData *response, NSError *error) {
        table.pullToRefreshView.lastUpdatedDate = [NSDate date];
        [table.pullToRefreshView performSelector:@selector(stopAnimating) withObject:nil afterDelay:0];
        
        if(error){
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Ошибка" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
            [alert show];
        }
        else{
            NSMutableArray *return_facts = [NSMutableArray arrayWithArray:[response objectFromJSONData]];
            if(return_facts.count){
                [[DataBase sharedManeger] addFacts:return_facts];
                [self addFacts];
                
                WBSuccessNoticeView *notice = [WBSuccessNoticeView successNoticeInView:self.view title:[NSString stringWithFormat:@"Добавлено %d фактов",return_facts.count]];
                [notice show];
            }
        }
    }];
}

-(void)loadMoreFacts{    
    int fact_id = [[[factsArray lastObject] valueForKey:@"fact_id"] intValue];
        
    [factsArray addObjectsFromArray:[[DataBase sharedManeger]getFacts:factCategory fromFact_id:fact_id factType:factsType]];
    
    [table reloadData];

    [self checkMoreAvailablesFacts];        
}

-(void)changeFactsType{
    [self addFacts];
}


-(void)addFacts{
    [factsArray removeAllObjects];
    [factsArray addObjectsFromArray:[[DataBase sharedManeger]getFacts:factCategory fromFact_id:0 factType:factsType]];
    
    [table setContentOffset:CGPointMake(0, 0)];
    [table reloadData];
    
    [self checkMoreAvailablesFacts];
}

-(void)checkMoreAvailablesFacts{
    int fact_id = [[[factsArray lastObject] valueForKey:@"fact_id"] intValue];
    
    BOOL available = [[DataBase sharedManeger] isMoreFactsAvailable:factCategory fromFact_id:fact_id factType:factsType];
    
    if(!available)
        table.showsInfiniteScrolling = FALSE;
    else
        table.showsInfiniteScrolling = YES; 
}

#pragma mark - IBActions

-(IBAction)onSegmentControl:(SDSegmentedControl*)sender{
    factsType = sender.selectedSegmentIndex;
    [self changeFactsType];
}

#pragma mark - UITableView

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return factsArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"Cell";

    ListOfFactsCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[ListOfFactsCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];                        
    }
    
    [cell setFact:[factsArray objectAtIndex:indexPath.row]];
        
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    DetailFact_VC *vc = [[DetailFact_VC alloc] initWithNibName:@"DetailFact_VC" bundle:nil];
    vc.fact_id = [[[factsArray objectAtIndex:indexPath.row] valueForKey:@"fact_id"] intValue];
    vc.fact_number = indexPath.row;
    vc.fact_type = factsType;
    vc.category_id = factCategory;
    vc.fact_mode = 1;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - notifications

-(void)registerNotifications{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onChangeFavorites:) name:@"CHANGE_FAVORITES" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onSetRead:) name:@"SET_READ" object:nil];
}

-(void)removeNotificatios{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"CHANGE_FAVORITES" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"SET_READ" object:nil];
}

-(void)onChangeFavorites:(NSNotification*)notification{
    int fact_number = [[notification.object valueForKey:@"fact_number"] intValue];
    int is_favorite = [[notification.object valueForKey:@"is_favorite"] intValue];
    
    if(fact_number>=factsArray.count)
        return;
    
    [[factsArray objectAtIndex:fact_number] setValue:[NSNumber numberWithInt:is_favorite] forKey:@"is_favorite"];
    
    [table reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:fact_number inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
}

-(void)onSetRead:(NSNotification*)notification{
    int fact_number = [notification.object intValue];
    
    if(fact_number>=factsArray.count)
        return;

    if(factsType!=Unread){
        [[factsArray objectAtIndex:fact_number] setValue:[NSNumber numberWithInt:1] forKey:@"is_read"];
        [table reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:fact_number inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    }
}

#pragma mark - Memory Management

- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
}

-(void)dealloc{
    [self removeNotificatios];
    table = nil;
    segmentedControl = nil;
    category_icon = nil;
    factsArray = nil;    
}

@end
